#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <openssl/aes.h>

#define MSG_LEN 256
/*
int gaia_aes_encrypt(char* in, char* key, char* out);
int gaia_aes_decrypt(char* in, char* key, char* out);

//just test
int main (int argc, char * argv[]) 
{
  if(argc < 2)
  {
    fprintf(stderr,"Please input encrypt string!\n");
    return 1;
  }
  // 加密密钥 
  char key[AES_BLOCK_SIZE];
  char SourceData[MSG_LEN];
  char DstData[MSG_LEN];
  int i = 0;

  memset((char *)key,"*&Eks_@+=!$%^739",AES_BLOCK_SIZE);
  //memset( (char *)SourceData,0,MSG_LEN);
  memset( (char *)DstData,0,MSG_LEN);

  //SourceData = argv[1];
  strcpy((char *)SourceData,argv[1]);

  if(gaia_aes_encrypt(SourceData,key,DstData))
  {
    fprintf(stderr,"encrypt error!\n");
    return 1;
  }

  printf("enc %d:",strlen((char*)DstData)); 
  
  for(i = 0;DstData[i];i++)
    printf("%x",(unsigned char)DstData[i]);

  printf("\n");

  memset( (char *)SourceData,'0',MSG_LEN);
  if(gaia_aes_decrypt(DstData,key,SourceData))
  {
    fprintf(stderr,"decrypt error!\n");
    return 1;
  }
  
  printf("SourceData: %s\n",SourceData);

  return 0;
}
*/

/********************************************************* 
 * 函数功能：加密 
 * 参数说明：in需要加密的字符串，key加密的密钥，out加密后的字符串
 * 返回值： 加密成功返回0，失败返回1
 *********************************************************/

int gaia_aes_encrypt(char* in, char* key, char* out)
{
  if(!in || !key || !out) 
    return 1;

  unsigned char iv[AES_BLOCK_SIZE];//加密的初始化向量
  int i = 0;

  for(i=0; i<AES_BLOCK_SIZE; ++i)//iv一般设置为全0,可以设置其他，但是加密解密要一样就行
    iv[i]=0;

  AES_KEY aes;
  if(AES_set_encrypt_key((unsigned char*)key, 128, &aes) < 0)
    return 1;
  

  int len=strlen(in);
  AES_cbc_encrypt((unsigned char*)in, (unsigned char*)out, len, &aes, iv, AES_ENCRYPT);

  return 0;
}

/*
 * 函数功能：解密函数 
 * 参数说明：in需要解密的字符串，key为解密密钥(要和加密密钥一致)，out是解密后的字符串
 * 返回值：  解密成功返回0，失败返回1
 */

int gaia_aes_decrypt(char* in, char* key, char* out)
{
  if(!in || !key || !out) 
    return 1;

  unsigned char iv[AES_BLOCK_SIZE];//加密的初始化向量
  int i = 0;

  for(i=0; i<AES_BLOCK_SIZE; ++i)//iv一般设置为全0,可以设置其他，但是加密解密要一样就行
    iv[i]=0;

  AES_KEY aes;
  if(AES_set_decrypt_key((unsigned char*)key, 128, &aes) < 0)
    return 1;
  
  int len=strlen(in);
  AES_cbc_encrypt((unsigned char*)in, (unsigned char*)out, len, &aes, iv, AES_DECRYPT);

  return 0;
}
